from openai import OpenAI

# 初始化 OpenAI 客户端
client = OpenAI(api_key="sk-1f2a103b336d401eae868c0941e07cac", base_url="https://api.deepseek.com")

# 初始化对话消息列表
messages = [
    {"role": "assistant", "content": "你是一个AI专家"}
]

while True:
    # 获取用户输入
    user_input = input("你: ")
    if user_input.lower() == 'quit':
        break
    elif user_input.lower().startswith('set_system '):
        # 提取新的系统角色内容
        new_system_content = user_input[11:]
        # 找到并更新系统消息
        for message in messages:
            if message["role"] == "system":
                message["content"] = new_system_content
                break
        print(f"系统角色已更新为: {new_system_content}")
        continue

    # 将用户输入添加到消息列表
    messages.append({"role": "user", "content": user_input})

    # 调用模型获取回复
    try:
        response = client.chat.completions.create(
            model="deepseek-chat",
            messages=messages,
            max_tokens=1024,
            temperature=0.7,
            stream=True,
        )

        # 获取模型回复内容

        for s in response:
            content = s.choices[0].delta.content
            if content is not None:
                print(content, end="")
                assistant_reply = content
        print()
        # 将模型回复添加到消息列表
        messages.append({"role": "assistant", "content": assistant_reply})
    except Exception as e:
        print(f"发生错误: {e}")
